package usersv

import (
	"database/sql"
	"go.uber.org/zap"
	"sync"
	"wzgames/internal/admin/adc"
	"wzgames/internal/admin/admindao"
	"wzgames/internal/admin/api/wzabind"
	"wzgames/internal/admin/model"
	"wzgames/internal/constant"
	"wzgames/internal/gloader"
	"wzgames/internal/model/user"
	"wzgames/internal/response"
	"wzgames/pkg/components/mysql"
	"wzgames/pkg/logger"
)

var (
	userSv *UserSV
	once   sync.Once
)

type UserSV struct {
	walletDs *mysql.DS
	userDs   *mysql.DS
}

func SV() *UserSV {
	if userSv == nil {
		once.Do(func() {
			userSv = &UserSV{}
			userSv.walletDs = gloader.CommMgr().GetDBProxy(constant.MysqlOfWallet)
			userSv.userDs = gloader.CommMgr().GetDBProxy(constant.MysqlOfUser)
		})
	}
	return userSv
}

func (sv *UserSV) GetUserList(adm *adc.Admin, req wzabind.WzUserReq) ([]*model.UserInfoEntity, int16) {
	dao := admindao.UserDao{Driver: sv.userDs.Ds()}
	offset := (req.Page - 1) * req.PageSize
	ret, err := dao.GetWzUsers(req, offset, req.PageSize)
	if err != nil {
		if err != sql.ErrNoRows {
			logger.Error("[UserSV] get wz user list Error on GetWzUsers", zap.Int64("AdminId", adm.AdminId()), zap.Error(err))
			return nil, response.ErrInternal
		}
	}

	return ret, 0
}

func (sv *UserSV) GetUserWallets(adm *adc.Admin, userId uint64) ([]*user.WalletEntity, int16) {
	dao := admindao.WalletDao{Driver: sv.walletDs.Ds()}
	ret, err := dao.GetUserWallets(userId)
	if err != nil {
		if err != sql.ErrNoRows {
			logger.Error("[UserSV] get wz user wallets Error on GetUserWallets", zap.Int64("AdminId", adm.AdminId()), zap.Uint64("UserId", userId), zap.Error(err))
			return nil, response.ErrInternal
		}
	}

	return ret, 0
}

func (sv *UserSV) GetUserWalletTransfers(adm *adc.Admin, req wzabind.WzWalletTransferReq) ([]*model.WalletTransfer, int16) {
	dao := admindao.WalletDao{Driver: sv.walletDs.Ds()}
	offset := (req.Page - 1) * req.PageSize
	ret, err := dao.GetUserWalletTransfers(offset, req)
	if err != nil {
		if err != sql.ErrNoRows {
			logger.Error("[UserSV] get wz user wallet transfers Error on GetUserWalletTransfers", zap.Int64("AdminId", adm.AdminId()), zap.Uint64("UserId", req.Uid), zap.Error(err))
			return nil, response.ErrInternal
		}
	}

	return ret, 0
}

func (sv *UserSV) GetUserGameLoginLogs(adm *adc.Admin, req wzabind.WzUserReq) ([]*model.UserGameLoginEntity, int16) {
	dao := admindao.UserDao{Driver: sv.userDs.Ds()}
	offset := (req.Page - 1) * req.PageSize
	ret, err := dao.GetWzUserLoginGameLog(req, offset)
	if err != nil {
		if err != sql.ErrNoRows {
			logger.Error("[UserSV] get wz user game login logs Error on GetWzUserLoginGameLog", zap.Int64("AdminId", adm.AdminId()), zap.Error(err))
			return nil, response.ErrInternal
		}
	}

	return ret, 0
}
